﻿// <copyright file="UserProviderCsvExtension.cs" company="Ecole Normale Supérieure">
// Released under GPLv2
// </copyright>
// <summary>Provide CSV import feature to IUserProvider.</summary>

namespace Sqwarea.Persistence.Csv
{
    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.IO;
    using LumenWorks.Framework.IO.Csv;

    /// <summary>
    /// Provide CSV import feature to IUserProvider.
    /// </summary>
    public static class UserProviderCsvExtension
    {
        /// <summary>
        /// Import users dictionnary with a CSV file.
        /// Headers :
        /// Id ; OpenId ; Nickname ; Language ; Email ; LastConnection ; RememberMeKey
        /// </summary>
        /// <param name="userProvider">The user provider</param>
        /// <param name="file">The CSV file</param>
        public static void ImportUsersFromCsv(this IUserProvider userProvider, string file)
        {
            using (CsvReader csv = new CsvReader(new StreamReader(file), true))
            {
                int fieldCount = csv.FieldCount;

                if (fieldCount != 7)
                {
                    throw new InvalidDataException(file);
                }

                while (csv.ReadNextRecord())
                {
                    var user = new User();

                    user.Id = int.Parse(csv[0], Tools.NumberFormat);
                    user.OpenId = csv[1];
                    user.Nickname = csv[2];
                    user.Language = csv[3];
                    user.Email = csv[4];
                    user.LastConnection = DateTime.Parse(csv[5], CultureInfo.InvariantCulture);
                    user.RemembranceSessions = new Dictionary<string, RemembranceSession>();
                    user.RemembranceSessions[csv[6]] = new RemembranceSession
                    {
                        CreationDate = DateTime.Now,
                        Key = csv[6]
                    };

                    userProvider.UpdateUser(user);
                }
            }
        }
    }
}